/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Tank.java]
 * Creation Date        [21-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_03_game.tankwar_local.version_1;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;

/**
 * 坦克
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Tank {

	/** 坦克初始化坐标 */
	private int x = MainFrame.GAME_WIDTH / 2;
	private int y = MainFrame.GAME_HEIGHT / 2;

	/** 坦克移动速度 */
	public static final int X_SPEED = 5;
	public static final int Y_SPEED = 5;

	/** 定义坦克方向 */
	enum Direction {
		LEFT, RIGHT, UP, DOWN, STOP
	}

	/** 标识方向键是否被按下 */
	private boolean l = false;
	private boolean r = false;
	private boolean u = false;
	private boolean d = false;

	/** 坦克默认的方向 */
	private Direction direction = Direction.STOP;

	public Tank() {
		this(MainFrame.GAME_WIDTH / 2, MainFrame.GAME_HEIGHT / 2);
	}

	public Tank(int x, int y) {
		this.x = x;
		this.y = y;
	}

	/**
	 * 绘制坦克
	 * 
	 * @param g
	 */
	public void paint(Graphics g) {
		// 获得原位置颜色
		Color color = g.getColor();
		// 设置坦克颜色
		g.setColor(Color.GREEN);
		g.fillRect(x, y, 30, 30);
		// 将前景色还原
		g.setColor(color);
		// 坦克移动
		move();
	}

	/**
	 * 处理键盘按下事件
	 * 
	 * @param e
	 */
	public void keyPressed(KeyEvent e) {
		// 获得按键信息
		int key = e.getKeyCode();
		switch (key) {
		case KeyEvent.VK_UP:
			u = true;
			break;
		case KeyEvent.VK_DOWN:
			d = true;
			break;
		case KeyEvent.VK_LEFT:
			l = true;
			break;
		case KeyEvent.VK_RIGHT:
			r = true;
			break;
		}

		setDirection();
	}

	/**
	 * 处理键盘释放事件
	 * 
	 * @param e
	 */
	public void keyReleased(KeyEvent e) {
		int key = e.getKeyCode();
		switch (key) {
		case KeyEvent.VK_UP:
			u = false;
			break;
		case KeyEvent.VK_DOWN:
			d = false;
			break;
		case KeyEvent.VK_LEFT:
			l = false;
			break;
		case KeyEvent.VK_RIGHT:
			r = false;
			break;
		}
		setDirection();
	}

	/**
	 * 设定坦克方向
	 */
	private void setDirection() {
		if (l && !r && !u && !d) {
			direction = Direction.LEFT;
		} else if (!l && r && !u && !d) {
			direction = Direction.RIGHT;
		} else if (!l && !r && u && !d) {
			direction = Direction.UP;
		} else if (!l && !r && !u && d) {
			direction = Direction.DOWN;
		} else if (!l && !r && !u && !d) {
			direction = Direction.STOP;
		}
	}

	/**
	 * 坦克移动
	 */
	private void move() {
		switch (direction) {
		case LEFT:
			x -= X_SPEED;
			break;
		case RIGHT:
			x += X_SPEED;
			break;
		case UP:
			y -= Y_SPEED;
			break;
		case DOWN:
			y += Y_SPEED;
			break;
		case STOP:
			break;
		}
	}
}
